/*
 * @Copyright: 2016 www.yyfax.com Inc. All rights reserved.
 */
package com.jaws.core.common.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.apache.commons.codec.binary.Base64;

/**
 * <p>
 * RSA 加密/解密/签名/校验 工具类
 * </p>
 * <p>
 * 罗纳德·李维斯特（Ron [R]ivest）、阿迪·萨莫尔（Adi [S]hamir）和伦纳德·阿德曼（Leonard [A]dleman）
 * </p>
 * <p>
 * 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/>
 * 由于非对称加密速度极其缓慢，一般文件不使用它来加密而是使用对称加密，<br/>
 * 非对称加密算法可以用来对对称加密的密钥加密，这样保证密钥的安全也就保证了数据的安全
 * 
 * @author jiangmy
 * @date 2016-12-02 09:26:21
 * @since v1.0.0
 */
public final class RSAUtil {

	/**
	 * 字节数据转字符串专用集合
	 */
	private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	/**
	 * 加密算法RSA
	 */
	public static final String CRIPT_ALGORITHM = "RSA";

	/**
	 * 签名算法
	 */
	public static final String SIGN_ALGORITHMS = "SHA1WithRSA";

	// public static final String SIGN_ALGORITHMS = "MD5withRSA";

	/**
	 * 随机生成密钥对,并写入到目录
	 * 
	 * @throws NoSuchAlgorithmException
	 */
	public static KeyPair genKeyPair(String filePath) throws NoSuchAlgorithmException {
		return genKeyPair(filePath + "/publicKey.keystore", filePath + "/privateKey.keystore");
	}

	/**
	 * 随机生成密钥对,并写入到文件
	 * 
	 * @throws NoSuchAlgorithmException
	 */
	public static KeyPair genKeyPair(String pubkeyFile, String prikeyFile) throws NoSuchAlgorithmException {
		KeyPair keyPair = genKeyPair();
		try {
			// 得到公钥字符串
			String publicKeyString = Base64.encodeBase64String(keyPair.getPublic().getEncoded());
			// 得到私钥字符串
			String privateKeyString = Base64.encodeBase64String(keyPair.getPrivate().getEncoded());
			// 将密钥对写入到文件
			try (FileWriter pubfw = new FileWriter(pubkeyFile)) {
				try (BufferedWriter pubbw = new BufferedWriter(pubfw)) {
					pubbw.write(publicKeyString);
					pubbw.flush();
				}
			}
			try (FileWriter prifw = new FileWriter(prikeyFile)) {
				try (BufferedWriter pribw = new BufferedWriter(prifw)) {
					pribw.write(privateKeyString);
					pribw.flush();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return keyPair;
	}

	/**
	 * 随机生成密钥对
	 * 
	 * @throws NoSuchAlgorithmException
	 */
	public static KeyPair genKeyPair() throws NoSuchAlgorithmException {
		// KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(CRIPT_ALGORITHM);
		// 初始化密钥对生成器，密钥大小为96-1024位
		keyPairGen.initialize(1024, new SecureRandom());
		// 生成一个密钥对，保存在keyPair中
		KeyPair keyPair = keyPairGen.generateKeyPair();
		// 得到私钥
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
		// 得到公钥
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
		return new KeyPair(publicKey, privateKey);
	}

	/**
	 * 从文件中输入流中加载公钥
	 * 
	 * @param in
	 *        公钥输入流
	 * @throws Exception
	 *         加载公钥时产生的异常
	 */
	public static String loadPublicKeyFromPath(String path) throws Exception {
		return loadPublicKeyFromFile(path + "/publicKey.keystore");
	}

	/**
	 * 从文件中输入流中加载公钥
	 * 
	 * @param in
	 *        公钥输入流
	 * @throws Exception
	 *         加载公钥时产生的异常
	 */
	public static String loadPublicKeyFromFile(String file) throws Exception {
		try (BufferedReader br = new BufferedReader(new FileReader(file))) {
			String readLine = null;
			StringBuilder sb = new StringBuilder();
			while ((readLine = br.readLine()) != null) {
				sb.append(readLine);
			}
			return sb.toString();
		} catch (IOException e) {
			throw new Exception("公钥数据流读取错误");
		} catch (NullPointerException e) {
			throw new Exception("公钥输入流为空");
		}
	}

	/**
	 * 从字符串中加载公钥
	 * 
	 * @param publicKeyStr
	 *        公钥数据字符串
	 * @throws Exception
	 *         加载公钥时产生的异常
	 */
	public static RSAPublicKey loadPublicKeyFromStr(String publicKeyStr) throws Exception {
		try {
			byte[] buffer = Base64.decodeBase64(publicKeyStr);
			KeyFactory keyFactory = KeyFactory.getInstance(CRIPT_ALGORITHM);
			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
			return (RSAPublicKey) keyFactory.generatePublic(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此算法");
		} catch (InvalidKeySpecException e) {
			throw new Exception("公钥非法");
		} catch (NullPointerException e) {
			throw new Exception("公钥数据为空");
		}
	}

	/**
	 * 从文件中加载私钥
	 * 
	 * @param keyFileName
	 *        私钥文件名
	 * @return 是否成功
	 * @throws Exception
	 */
	public static String loadPrivateKeyFromPath(String path) throws Exception {
		return loadPrivateKeyFromFile(path + "/privateKey.keystore");
	}

	/**
	 * 从文件中加载私钥
	 * 
	 * @param keyFileName
	 *        私钥文件名
	 * @return 是否成功
	 * @throws Exception
	 */
	public static String loadPrivateKeyFromFile(String file) throws Exception {
		try (BufferedReader br = new BufferedReader(new FileReader(file))) {
			String readLine = null;
			StringBuilder sb = new StringBuilder();
			while ((readLine = br.readLine()) != null) {
				sb.append(readLine);
			}
			return sb.toString();
		} catch (IOException e) {
			throw new Exception("私钥数据读取错误:" + file);
		} catch (NullPointerException e) {
			throw new Exception("私钥输入流为空:" + file);
		}
	}

	public static RSAPrivateKey loadPrivateKeyFromStr(String privateKeyStr) throws Exception {
		try {
			byte[] buffer = Base64.decodeBase64(privateKeyStr);
			PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
			KeyFactory keyFactory = KeyFactory.getInstance(CRIPT_ALGORITHM);
			return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此算法");
		} catch (InvalidKeySpecException e) {
			throw new Exception("私钥非法");
		} catch (NullPointerException e) {
			throw new Exception("私钥数据为空");
		}
	}

	public static String privateKeyToStr(PrivateKey prikey) {
		return Base64.encodeBase64String(prikey.getEncoded());
	}

	public static String publickKeyToStr(PublicKey pubkey) {
		return Base64.encodeBase64String(pubkey.getEncoded());
	}

	public static KeyPair loadKeyPairFromStr(String publickeyStr, String privateKeyStr) throws Exception {
		return new KeyPair(loadPublicKeyFromStr(publickeyStr), loadPrivateKeyFromStr(privateKeyStr));
	}

	public static KeyPair loadKeyPairFromFile(String pubkeyPath, String prikeyPath) throws Exception {
		return loadKeyPairFromStr(loadPublicKeyFromFile(pubkeyPath), loadPrivateKeyFromFile(prikeyPath));
	}

	/**
	 * 公钥加密过程
	 * 
	 * @param publicKey
	 *        公钥
	 * @param plainTextData
	 *        明文数据
	 * @return
	 * @throws Exception
	 *         加密过程中的异常信息
	 */
	public static byte[] encrypt(PublicKey publicKey, byte[] plainTextData) throws Exception {
		if (publicKey == null) {
			throw new Exception("加密公钥为空, 请设置");
		}
		Cipher cipher = null;
		try {
			// 使用默认RSA
			cipher = Cipher.getInstance(CRIPT_ALGORITHM);
			// cipher= Cipher.getInstance(Algorithm, new BouncyCastleProvider());
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			byte[] output = cipher.doFinal(plainTextData);
			return output;
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此加密算法");
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
			return null;
		} catch (InvalidKeyException e) {
			throw new Exception("加密公钥非法,请检查");
		} catch (IllegalBlockSizeException e) {
			throw new Exception("明文长度非法");
		} catch (BadPaddingException e) {
			throw new Exception("明文数据已损坏");
		}
	}

	/**
	 * 私钥加密过程
	 * 
	 * @param privateKey
	 *        私钥
	 * @param plainTextData
	 *        明文数据
	 * @return
	 * @throws Exception
	 *         加密过程中的异常信息
	 */
	public static byte[] encrypt(PrivateKey privateKey, byte[] plainTextData) throws Exception {
		if (privateKey == null) {
			throw new Exception("加密私钥为空, 请设置");
		}
		Cipher cipher = null;
		try {
			// 使用默认RSA
			cipher = Cipher.getInstance(CRIPT_ALGORITHM);
			cipher.init(Cipher.ENCRYPT_MODE, privateKey);
			byte[] output = cipher.doFinal(plainTextData);
			return output;
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此加密算法");
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
			return null;
		} catch (InvalidKeyException e) {
			throw new Exception("加密私钥非法,请检查");
		} catch (IllegalBlockSizeException e) {
			throw new Exception("明文长度非法");
		} catch (BadPaddingException e) {
			throw new Exception("明文数据已损坏");
		}
	}

	public static String decrypt(PrivateKey privateKey, String base64) throws Exception {
		return new String(decrypt(privateKey, Base64.decodeBase64(base64)));
	}

	/**
	 * 私钥解密过程
	 * 
	 * @param privateKey
	 *        私钥
	 * @param cipherData
	 *        密文数据
	 * @return 明文
	 * @throws Exception
	 *         解密过程中的异常信息
	 */
	public static byte[] decrypt(PrivateKey privateKey, byte[] cipherData) throws Exception {
		if (privateKey == null) {
			throw new Exception("解密私钥为空, 请设置");
		}
		Cipher cipher = null;
		try {
			// 使用默认RSA
			cipher = Cipher.getInstance(CRIPT_ALGORITHM);
			// cipher= Cipher.getInstance(Algorithm, new BouncyCastleProvider());
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			byte[] output = cipher.doFinal(cipherData);
			return output;
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此解密算法");
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
			return null;
		} catch (InvalidKeyException e) {
			throw new Exception("解密私钥非法,请检查");
		} catch (IllegalBlockSizeException e) {
			throw new Exception("密文长度非法");
		} catch (BadPaddingException e) {
			throw new Exception("密文数据已损坏");
		}
	}

	/**
	 * 公钥解密过程
	 * 
	 * @author jiangmy
	 * @date 2016-12-02 09:44:19
	 * @param publicKey
	 * @param cipherText 私钥加密后的Base64密文
	 * @return
	 * @throws Exception
	 */
	public static byte[] decrypt(PublicKey publicKey, String cipherBase64Text) throws Exception {
		return decrypt(publicKey, Base64.decodeBase64(cipherBase64Text));
	}

	/**
	 * 公钥解密过程
	 * 
	 * @author jiangmy
	 * @date 2016-12-02 09:44:33
	 * @param publicKey 公钥
	 * @param cipherData 私钥加密密文
	 * @return
	 * @throws Exception
	 */
	public static byte[] decrypt(PublicKey publicKey, byte[] cipherData) throws Exception {
		if (publicKey == null) {
			throw new Exception("解密公钥为空, 请设置");
		}
		Cipher cipher = null;
		try {
			// 使用默认RSA
			cipher = Cipher.getInstance(CRIPT_ALGORITHM);
			// cipher= Cipher.getInstance(Algorithm, new org.bouncycastle.jce.provider.BouncyCastleProvider());
			cipher.init(Cipher.DECRYPT_MODE, publicKey);
			byte[] output = cipher.doFinal(cipherData);
			return output;
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此解密算法");
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
			return null;
		} catch (InvalidKeyException e) {
			throw new Exception("解密公钥非法,请检查");
		} catch (IllegalBlockSizeException e) {
			throw new Exception("密文长度非法");
		} catch (BadPaddingException e) {
			throw new Exception("密文数据已损坏");
		}
	}

	/**
	 * 字节数据转十六进制字符串
	 * 
	 * @param data
	 *        输入数据
	 * @return 十六进制内容
	 */
	public static String byteArrayToString(byte[] data) {
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < data.length; i++) {
			// 取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
			stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);
			// 取出字节的低四位 作为索引得到相应的十六进制标识符
			stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
			if (i < data.length - 1) {
				stringBuilder.append(' ');
			}
		}
		return stringBuilder.toString();
	}

	public static boolean verify(String pubKey, String content, String sign) throws Exception {
		return verify(loadPublicKeyFromStr(pubKey), content, sign);
	}

	public static boolean verify(PublicKey pubKey, String content, String sign) {
		return verify(pubKey, content, sign, Charset.defaultCharset().name());
	}

	public static boolean verify(PublicKey pubKey, String content, String sign, String encode) {
		try {
			java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
			signature.initVerify(pubKey);
			signature.update(content.getBytes(encode));
			boolean bverify = signature.verify(Base64.decodeBase64(sign));
			return bverify;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 私钥签名
	 * 
	 * @author jiangmy
	 * @date 2016-12-02 10:32:51
	 * @param priKey
	 * @param content
	 * @return
	 * @throws Exception
	 */
	public static String sign(String priKey, String content) throws Exception {
		return sign(loadPrivateKeyFromStr(priKey), content);
	}

	public static String sign(PrivateKey priKey, String content) {
		return sign(priKey, content, Charset.defaultCharset().name());
	}

	/**
	 * RSA签名
	 * 
	 * @param privateKey 商户私钥
	 * @param content 待签名数据
	 * @param encode 字符集编码
	 * @return 签名值
	 */
	public static String sign(PrivateKey priKey, String content, String encode) {
		try {
			java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
			signature.initSign(priKey);
			signature.update(content.getBytes(encode));
			//
			byte[] signed = signature.sign();
			return Base64.encodeBase64String(signed);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
